function getDaysInMonth(date) {
  if (typeof date === 'string') {
    date = new Date(date)
  }
  if (isNaN(date.getTime())) {
    throw new Error('Invalid date')
  }
  const nextMonthFirstDate = new Date(date.getFullYear(), date.getMonth() + 1, 0)
  return nextMonthFirstDate.getDate()
}

/**
 * 根据出生日期返回年龄
 * options 配置项
 * type
 * 1: 简单计算，默认
 * 2: 详细计算，仅限于1岁之前
 * 3: 其他方式，可扩展
 *
 * 示例：
 * type为2
 * birthdate 2023-12-05 today 2024-01-04 输出 30天
 * birthdate 2023-12-03 today 2024-01-04 输出 1个月
 * birthdate 2023-11-05 today 2024-01-04 输出 1个月
 * birthdate 2023-11-04 today 2024-01-04 输出 2个月
 * birthdate 2023-12-05 today 2024-01-04 输出 30天
 * birthdate 2024-01-06 today 2024-02-04 输出 31 + 4 - 6 = 29天
 * birthdate 2023-04-05 today 2024-07-04 输出 2个月
 */
export function calculateAge(birthdate, options) {
  options = options || { type: 1 }
  // 确保birthdate是有效的日期格式，例如 "YYYY-MM-DD"
  const birthDate = new Date(birthdate)
  if (isNaN(birthDate.getTime())) {
    throw new Error('Invalid birthdate format')
  }

  // 获取当前日期
  const today = new Date()
  if (birthDate > today) {
    throw new Error('出生日期大于当天')
  }

  // 计算年龄
  let age = today.getFullYear() - birthDate.getFullYear()
  // 检查是否已过今年的生日
  const m = today.getMonth() - birthDate.getMonth()
  const d = today.getDate() - birthDate.getDate()
  if (m < 0) {
    age--
  }

  if (options.type === 1) {
    if (age === 0) {
      age = '小于1岁'
    } else {
      age = `${age}岁`
    }
  } else if (options.type === 2) {
    if (age === 0) {
      // 如果小于1个月，则单位为天，否则单位为月
      if (m < 0) {
        if (Math.abs(m) === 11) {
          if (d < 0) {
            age = `${getDaysInMonth(birthDate) - birthDate.getDate() + today.getDate()}天`
          } else if (d >= 0) {
            age = `1个月`
          }
        } else if (d < 0) {
          console.log('3')
          age = `${12 + m - 1}个月`
        } else {
          console.log('7')
          age = `${12 + m}个月`
        }
      } else if (m === 0) {
        console.log('4')
        age = `${d}天`
      } else if (m === 1 && d < 0) {
        console.log('5')
        age = `${getDaysInMonth(birthDate) - birthDate.getDate() + today.getDate()}天`
      } else {
        console.log('6')
        age = `${m}个月`
      }
    } else {
      age = `${age}岁`
    }
  }
  return age
}
